package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.dto.AIPaperGenerateDTO;
import com.eduplatform.dto.PaperDTO;
import com.eduplatform.dto.PaperQuestionDTO;
import com.eduplatform.entity.Paper;
import com.eduplatform.entity.PaperQuestion;
import com.eduplatform.entity.Question;
import com.eduplatform.entity.Subject;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.PaperMapper;
import com.eduplatform.mapper.PaperQuestionMapper;
import com.eduplatform.mapper.QuestionMapper;
import com.eduplatform.mapper.SubjectMapper;
import com.eduplatform.mapper.UserMapper;
import com.eduplatform.service.PaperService;
import com.eduplatform.service.SubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 试卷Service实现类
 */
@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {

    @Autowired
    private PaperQuestionMapper paperQuestionMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SubjectService subjectService;

    @Override
    public IPage<PaperDTO> pagePapers(int page, int size, Long subjectId, Integer educationLevel, Integer status,
            String keyword) {
        Page<Paper> paperPage = new Page<>(page, size);

        LambdaQueryWrapper<Paper> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (subjectId != null) {
            wrapper.eq(Paper::getSubjectId, subjectId);
        }

        if (educationLevel != null) {
            wrapper.eq(Paper::getEducationLevel, educationLevel);
        }

        if (status != null) {
            wrapper.eq(Paper::getStatus, status);
        }

        if (StringUtils.hasText(keyword)) {
            wrapper.like(Paper::getTitle, keyword);
        }

        // 按创建时间降序排序
        wrapper.orderByDesc(Paper::getCreateTime);

        // 执行分页查询
        IPage<Paper> result = page(paperPage, wrapper);

        // 转换为DTO对象
        IPage<PaperDTO> dtoPage = result.convert(this::convertToDTO);

        // 批量查询学科和创建人信息
        if (!dtoPage.getRecords().isEmpty()) {
            // 获取所有学科ID和创建人ID
            List<Long> subjectIds = dtoPage.getRecords().stream()
                    .map(PaperDTO::getSubjectId)
                    .distinct()
                    .collect(Collectors.toList());

            List<Long> creatorIds = dtoPage.getRecords().stream()
                    .map(PaperDTO::getCreatorId)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询学科信息
            List<Subject> subjects = subjectMapper.selectBatchIds(subjectIds);
            Map<Long, String> subjectMap = subjects.stream()
                    .collect(Collectors.toMap(Subject::getId, Subject::getName));

            // 批量查询创建人信息
            List<User> users = userMapper.selectBatchIds(creatorIds);
            Map<Long, String> userMap = users.stream()
                    .collect(Collectors.toMap(User::getId, User::getUsername));

            // 设置学科名称和创建人姓名
            for (PaperDTO dto : dtoPage.getRecords()) {
                dto.setSubjectName(subjectMap.getOrDefault(dto.getSubjectId(), ""));
                dto.setCreatorName(userMap.getOrDefault(dto.getCreatorId(), ""));
            }
        }

        return dtoPage;
    }

    @Override
    public PaperDTO getPaperDetail(Long id) {
        Paper paper = getById(id);
        if (paper == null) {
            return null;
        }

        PaperDTO dto = convertToDTO(paper);

        // 查询学科信息
        Subject subject = subjectMapper.selectById(paper.getSubjectId());
        if (subject != null) {
            dto.setSubjectName(subject.getName());
        }

        // 查询创建人信息
        User user = userMapper.selectById(paper.getCreatorId());
        if (user != null) {
            dto.setCreatorName(user.getUsername());
        }

        // 查询试卷题目
        LambdaQueryWrapper<PaperQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperQuestion::getPaperId, id);
        wrapper.orderByAsc(PaperQuestion::getQuestionType);
        wrapper.orderByAsc(PaperQuestion::getQuestionNumber);
        List<PaperQuestion> paperQuestions = paperQuestionMapper.selectList(wrapper);

        if (!paperQuestions.isEmpty()) {
            // 获取所有题目ID
            List<Long> questionIds = paperQuestions.stream()
                    .map(PaperQuestion::getQuestionId)
                    .collect(Collectors.toList());

            // 批量查询题目信息
            List<Question> questions = questionMapper.selectBatchIds(questionIds);
            Map<Long, Question> questionMap = questions.stream()
                    .collect(Collectors.toMap(Question::getId, q -> q));

            // 转换为DTO对象
            List<PaperQuestionDTO> questionDTOs = new ArrayList<>();
            for (PaperQuestion pq : paperQuestions) {
                PaperQuestionDTO pqDTO = new PaperQuestionDTO();
                BeanUtils.copyProperties(pq, pqDTO);

                // 设置题目信息
                Question question = questionMap.get(pq.getQuestionId());
                if (question != null) {
                    pqDTO.setContent(question.getContent());
                    pqDTO.setOptions(question.getOptions());
                    pqDTO.setAnswer(question.getAnswer());
                    pqDTO.setAnalysis(question.getAnalysis());
                }

                questionDTOs.add(pqDTO);
            }

            dto.setQuestions(questionDTOs);
        }

        return dto;
    }

    @Override
    @Transactional
    public boolean addPaper(PaperDTO paperDTO) {
        Paper paper = new Paper();
        BeanUtils.copyProperties(paperDTO, paper);

        // 设置初始状态为草稿
        paper.setStatus(0);

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        paper.setCreateTime(now);
        paper.setUpdateTime(now);

        // 保存试卷
        boolean result = save(paper);

        // 保存试卷题目
        if (result && paperDTO.getQuestions() != null && !paperDTO.getQuestions().isEmpty()) {
            List<PaperQuestion> paperQuestions = new ArrayList<>();
            int totalScore = 0;

            for (PaperQuestionDTO questionDTO : paperDTO.getQuestions()) {
                PaperQuestion paperQuestion = new PaperQuestion();
                BeanUtils.copyProperties(questionDTO, paperQuestion);
                paperQuestion.setPaperId(paper.getId());

                paperQuestions.add(paperQuestion);
                totalScore += questionDTO.getScore();
            }

            // 批量保存试卷题目
            for (PaperQuestion paperQuestion : paperQuestions) {
                paperQuestionMapper.insert(paperQuestion);
            }

            // 更新试卷总分
            paper.setTotalScore(totalScore);
            updateById(paper);
        }

        return result;
    }

    @Override
    @Transactional
    public boolean updatePaper(PaperDTO paperDTO) {
        Paper paper = getById(paperDTO.getId());
        if (paper == null) {
            return false;
        }

        // 只有草稿状态的试卷才能修改
        if (paper.getStatus() != 0) {
            return false;
        }

        BeanUtils.copyProperties(paperDTO, paper);

        // 更新时间
        paper.setUpdateTime(LocalDateTime.now());

        // 更新试卷
        boolean result = updateById(paper);

        // 更新试卷题目
        if (result && paperDTO.getQuestions() != null) {
            // 删除原有题目
            LambdaQueryWrapper<PaperQuestion> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PaperQuestion::getPaperId, paper.getId());
            paperQuestionMapper.delete(wrapper);

            // 添加新题目
            List<PaperQuestion> paperQuestions = new ArrayList<>();
            int totalScore = 0;

            for (PaperQuestionDTO questionDTO : paperDTO.getQuestions()) {
                PaperQuestion paperQuestion = new PaperQuestion();
                BeanUtils.copyProperties(questionDTO, paperQuestion);
                paperQuestion.setPaperId(paper.getId());

                paperQuestions.add(paperQuestion);
                totalScore += questionDTO.getScore();
            }

            // 批量保存试卷题目
            for (PaperQuestion paperQuestion : paperQuestions) {
                paperQuestionMapper.insert(paperQuestion);
            }

            // 更新试卷总分
            paper.setTotalScore(totalScore);
            updateById(paper);
        }

        return result;
    }

    @Override
    @Transactional
    public boolean deletePaper(Long id) {
        // 删除试卷题目
        LambdaQueryWrapper<PaperQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperQuestion::getPaperId, id);
        paperQuestionMapper.delete(wrapper);

        // 删除试卷
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean publishPaper(Long id) {
        Paper paper = getById(id);
        if (paper == null) {
            return false;
        }

        // 检查试卷是否有题目
        LambdaQueryWrapper<PaperQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperQuestion::getPaperId, id);
        Long count = paperQuestionMapper.selectCount(wrapper);
        if (count == 0) {
            return false;
        }

        // 更新状态为已发布
        paper.setStatus(1);
        paper.setUpdateTime(LocalDateTime.now());

        return updateById(paper);
    }

    /**
     * 将实体对象转换为DTO对象
     */
    private PaperDTO convertToDTO(Paper paper) {
        PaperDTO dto = new PaperDTO();
        BeanUtils.copyProperties(paper, dto);
        return dto;
    }

    @Override
    @Transactional
    public PaperDTO generateAIPaper(AIPaperGenerateDTO generateDTO, Long creatorId) {
        // 创建试卷基本信息
        PaperDTO paperDTO = new PaperDTO();
        paperDTO.setTitle(generateDTO.getTitle());
        paperDTO.setSubjectId(generateDTO.getSubjectId());
        paperDTO.setEducationLevel(generateDTO.getEducationLevel());
        paperDTO.setDuration(generateDTO.getDuration());
        paperDTO.setTotalScore(generateDTO.getTotalScore());
        paperDTO.setCreatorId(creatorId);
        paperDTO.setDescription("AI智能生成试卷");

        // 准备AI生成试卷的题目
        List<PaperQuestionDTO> questions = generateAIQuestions(generateDTO, creatorId);
        paperDTO.setQuestions(questions);

        // 保存试卷
        Paper paper = new Paper();
        BeanUtils.copyProperties(paperDTO, paper);

        // 设置初始状态为草稿
        paper.setStatus(0);

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        paper.setCreateTime(now);
        paper.setUpdateTime(now);

        // 保存试卷
        boolean result = save(paper);

        // 保存试卷题目
        if (result && paperDTO.getQuestions() != null && !paperDTO.getQuestions().isEmpty()) {
            List<PaperQuestion> paperQuestions = new ArrayList<>();
            int totalScore = 0;

            for (PaperQuestionDTO questionDTO : paperDTO.getQuestions()) {
                PaperQuestion paperQuestion = new PaperQuestion();
                BeanUtils.copyProperties(questionDTO, paperQuestion);
                paperQuestion.setPaperId(paper.getId());

                paperQuestions.add(paperQuestion);
                totalScore += questionDTO.getScore();
            }

            // 批量保存试卷题目
            for (PaperQuestion paperQuestion : paperQuestions) {
                paperQuestionMapper.insert(paperQuestion);
            }

            // 更新试卷总分
            paper.setTotalScore(totalScore);
            updateById(paper);
        }

        // 设置生成的试卷ID
        paperDTO.setId(paper.getId());

        // 返回带ID的试卷数据
        return paperDTO;
    }

    @Override
    public List<Object> getAISupportedSubjects() {
        // 实际环境中可能需要进一步过滤哪些学科支持AI生成
        // 这里先简单返回所有学科
        return subjectService.list().stream()
                .map(subject -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", subject.getId());
                    map.put("name", subject.getName());
                    map.put("level", subject.getLevel());
                    return map;
                })
                .collect(Collectors.toList());
    }

    /**
     * 模拟AI生成试卷题目
     * 
     * @param generateDTO 生成参数
     * @param creatorId   创建者ID
     * @return 生成的题目列表
     */
    private List<PaperQuestionDTO> generateAIQuestions(AIPaperGenerateDTO generateDTO, Long creatorId) {
        List<PaperQuestionDTO> questions = new ArrayList<>();

        // 计算每道题目的平均分数
        int totalQuestionCount = generateDTO.getQuestionTypes().stream()
                .mapToInt(AIPaperGenerateDTO.QuestionTypeConfig::getCount)
                .sum();
        int avgScore = generateDTO.getTotalScore() / totalQuestionCount;
        int remainingScore = generateDTO.getTotalScore() % totalQuestionCount;

        // 生成不同类型的题目
        int questionNumber = 1;

        for (AIPaperGenerateDTO.QuestionTypeConfig config : generateDTO.getQuestionTypes()) {
            int questionType = config.getType();
            int count = config.getCount();

            for (int i = 0; i < count; i++) {
                PaperQuestionDTO question = new PaperQuestionDTO();
                question.setQuestionType(questionType);
                question.setQuestionNumber(questionNumber++);

                // 分配分数 (最后一道题拿到剩余的分数)
                int score = avgScore;
                if (questionNumber == totalQuestionCount + 1 && remainingScore > 0) {
                    score += remainingScore;
                }
                question.setScore(score);

                // 根据题型生成题目内容并创建Question记录
                Question questionEntity = createQuestionEntity(questionType, generateDTO, creatorId);
                // 保存Question实体到数据库并获取ID
                questionMapper.insert(questionEntity);

                // 设置questionId
                question.setQuestionId(questionEntity.getId());

                // 设置题目内容
                question.setContent(questionEntity.getContent());
                question.setOptions(questionEntity.getOptions());
                question.setAnswer(questionEntity.getAnswer());
                question.setAnalysis(questionEntity.getAnalysis());

                questions.add(question);
            }
        }

        return questions;
    }

    /**
     * 创建Question实体对象
     * 
     * @param questionType 题目类型
     * @param generateDTO  生成参数
     * @param creatorId    创建者ID
     * @return Question实体对象
     */
    private Question createQuestionEntity(int questionType, AIPaperGenerateDTO generateDTO, Long creatorId) {
        Question question = new Question();

        // 获取学科名称
        Subject subject = subjectMapper.selectById(generateDTO.getSubjectId());
        String subjectName = subject != null ? subject.getName() : "";
        Random random = new Random();

        // 设置基本信息
        question.setType(questionType);
        question.setSubjectId(generateDTO.getSubjectId());
        question.setEducationLevel(generateDTO.getEducationLevel());
        question.setDifficulty(generateDTO.getDifficulty());
        question.setCreatorId(creatorId); // 使用当前用户ID作为创建者ID

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        question.setCreateTime(now);
        question.setUpdateTime(now);

        // 根据不同题型生成内容
        switch (questionType) {
            case 1: // 单选题
                question.setContent(generateSingleChoiceQuestion(subjectName, generateDTO.getKeywords(),
                        generateDTO.getDifficulty()));
                question.setOptions("[{\"label\":\"A\",\"content\":\"选项A\"},{\"label\":\"B\",\"content\":\"选项B\"}," +
                        "{\"label\":\"C\",\"content\":\"选项C\"},{\"label\":\"D\",\"content\":\"选项D\"}]");
                question.setAnswer("A");
                question.setAnalysis("这是单选题的解析");
                break;
            case 2: // 多选题
                question.setContent(generateMultiChoiceQuestion(subjectName, generateDTO.getKeywords(),
                        generateDTO.getDifficulty()));
                question.setOptions("[{\"label\":\"A\",\"content\":\"选项A\"},{\"label\":\"B\",\"content\":\"选项B\"}," +
                        "{\"label\":\"C\",\"content\":\"选项C\"},{\"label\":\"D\",\"content\":\"选项D\"}]");
                question.setAnswer("A,B");
                question.setAnalysis("这是多选题的解析");
                break;
            case 3: // 判断题
                question.setContent(
                        generateTrueFalseQuestion(subjectName, generateDTO.getKeywords(), generateDTO.getDifficulty()));
                question.setOptions("[{\"label\":\"T\",\"content\":\"正确\"},{\"label\":\"F\",\"content\":\"错误\"}]");
                question.setAnswer(random.nextBoolean() ? "T" : "F");
                question.setAnalysis("这是判断题的解析");
                break;
            case 4: // 填空题
                question.setContent(
                        generateFillBlankQuestion(subjectName, generateDTO.getKeywords(), generateDTO.getDifficulty()));
                question.setOptions("[]");
                question.setAnswer("答案");
                question.setAnalysis("这是填空题的解析");
                break;
            case 5: // 简答题
                question.setContent(
                        generateEssayQuestion(subjectName, generateDTO.getKeywords(), generateDTO.getDifficulty()));
                question.setOptions("[]");
                question.setAnswer("参考答案内容");
                question.setAnalysis("这是简答题的解析");
                break;
        }

        return question;
    }

    /**
     * 以下方法用于模拟生成不同类型的题目
     * 实际项目中应该调用大模型API进行生成
     */
    private String generateSingleChoiceQuestion(String subject, String keywords, Integer difficulty) {
        return String.format("【%s】单选题: 关于%s的问题，请选择正确的选项", subject, keywords);
    }

    private String generateMultiChoiceQuestion(String subject, String keywords, Integer difficulty) {
        return String.format("【%s】多选题: 关于%s的问题，请选择所有正确的选项", subject, keywords);
    }

    private String generateTrueFalseQuestion(String subject, String keywords, Integer difficulty) {
        return String.format("【%s】判断题: 关于%s的陈述，判断对错", subject, keywords);
    }

    private String generateFillBlankQuestion(String subject, String keywords, Integer difficulty) {
        return String.format("【%s】填空题: 关于%s的问题，填写答案", subject, keywords);
    }

    private String generateEssayQuestion(String subject, String keywords, Integer difficulty) {
        return String.format("【%s】简答题: 请简要分析%s相关的问题", subject, keywords);
    }
}